package event;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class EventHandler {
	private static final EventHandler EVENT_HANDLER = new EventHandler();
	
	private final BlockingQueue<Runnable> queue;
	private final Thread workThread;
	
	private boolean terminate;
	
	private EventHandler() {
		this.queue = new LinkedBlockingQueue<Runnable>();
		this.workThread = new Thread() {
			@Override
			public void run() {
				while (!terminate) {
					try {
						queue.take().run();
					} catch (InterruptedException e) {
						if (!terminate) {
							e.printStackTrace();
						}
					}
				}
			}
		};
		this.terminate = false;
		workThread.start();
	}
	
	public void accept(Runnable r) {
		try {
			queue.put(r);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void terminate() {
		terminate = true;
		workThread.interrupt();
	}
	
	public static EventHandler getEventHandler() {
		return EVENT_HANDLER;
	}
}
